import msg from "../../../utils/msg";
import { uploadPic, userUpdate } from "../../../utils/request/api";
import User from "../../../utils/user"
import { filePath1 } from "../../../utils/request/route";
import Notify from "../../../miniprogram_npm/@vant/weapp/notify/notify";
// pages/user/info/info.ts
Page({

  /**
   * 页面的初始数据
   */
  data: {
    user:{} as User,
    is_changed:false,
    getPhone: false,
    filePath1,
    nameErr:false,
  },
  submit:async function(){
    if(!this.data.user.name){
      msg.show('请输入用户名', ''); return;
    }
    let user = this.data.user;
    await user.update();
    user.setStorage();
    Notify({ type: 'success', message: '个人信息更新成功' });
    this.setData({
      is_changed:false,
    });
  },
  onClose() {
    this.setData({ getPhone: false });
  },
  getPhoneNumber(e: any) {
    let code = e.detail.code;
    if (!code) {
      msg.show('请您授权手机号', '否则无法绑定(╥﹏╥)'); return;
    }
    let user = new User;
    user.Login(code);
  },
  phone: async function(){
    this.setData({ getPhone: true });
  },
  inputName(e:any){
    let input = e.detail;
    this.setData({
      ['user.name']:input,
      is_changed:true,
      nameErr:!input,
    });
  },
  //上传头像
  headPic:async function(){
    let user = this.data.user;
    if (!user.checkLogin(1)) return;
    let self = this;
    await msg.confirm('是否更换头像', '');
    wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      sourceType: ['album', 'camera'],
      camera: 'back',
      async success(res: any) {
        //console.log(res.tempFiles[0].tempFilePath)
        //上传后端，命名为改代表的userid
        msg.Loading();
        let res_upload = await uploadPic(res.tempFiles[0].tempFilePath, 'Filedata')
          .then((res: any) => { return res; });
        if (res_upload.statusCode != 200) {
          msg.show('服务器维护中', '请稍后再试'); return;
        }
        let data = res_upload.data;
        if (typeof data == 'string') data = JSON.parse(data);
        let fileName = data.savename;
        user.head_pic = fileName;
        user.setStorage();
        //user.update();//上传用户信息
        self.setData({
          user: user,
          is_changed:true,
        });
        msg.hideLoading();
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    let user = new User;
    this.setData({
      user,
    });
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})